// packageA/pages/partEnterEdit/partEnterEdit.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //修改信息
    editInfo:null,
    //登录用户
    user:null,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //循环表单列表
    loopList:[],
    //是否只读
    isRead: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ 
      user: app.globalData.userInfo 
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('配件入库修改-传参');
      console.log(paramObj);  

      if(paramObj.id){
        //获取配件入库信息
        this.getInfo(paramObj.id);
      }

      if(paramObj.isRead){
        this.setData({ 
          isRead: paramObj.isRead
        })
      }
    }
  },

  //获取配件入库信息
  getInfo(id){
    let param = {
      isAuth: false,
      className: 'inStorageOrder',
      data: {
        id: id,
        selectFields: ['id', 'inStorageType', 'factory', 'logistics', 'type', 'purchaseOrder', 'buyer', 'orderNo','depot', 'state', 'inStorageParts', 'inputDateTime', 'operator', 'remark', 'purchaseOrder','parts', 'server', 'detail', 'orderPersonnel', 'clerk']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];

        //采购时间
        if(result.purchaseOrder && result.purchaseOrder.purchaseTime){
          result.purchaseOrder.purchaseTime=util.timeFormat(result.purchaseOrder.purchaseTime);
        }
        
        //总金额
        let totalPrice=0;

        //配件
        if(result.detail){
          let loopList=result.detail;
          
          loopList.forEach(item => {
            //名称和规格
            if(item.partName && (item.partName.indexOf("&")>-1)){
              let arr=item.partName.split("&");
              item.self_name=arr[0];
              item.self_spec=arr[1];
            }

            //计算金额
            let currentTotalPrice = item.shippedNum * item.purchasingPrice;
            //这里不用self_命名，因为这个值入库时要传过去
            item.currentTotalPrice=currentTotalPrice;

            //计算总金额
            totalPrice+=currentTotalPrice;
          });

          this.setData({
            loopList: loopList
          })
        }

        result.self_partTotal=totalPrice;
        
        this.setData({
          editInfo: result
        })

        console.log('配件入库信息');
        console.log(result);  
      }
    }).catch((error) => {
    })
  },

  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo;
    let user=app.globalData.userInfo; 
    let loopList=td.loopList;

    let param={
      //不改的信息
      id: editInfo.id,
      orderNo: editInfo.orderNo,      
      depot: editInfo.depot,
      inputDateTime: editInfo.inputDateTime,
      inStorageType: editInfo.inStorageType,
      purchaseOrder: editInfo.purchaseOrder,
      buyer: editInfo.buyer,
      factory: editInfo.factory,
      clerk: editInfo.clerk,

      //操作员-当前用户
      operator: {
        id: user.id,
        name: user.userName
      },
      //备注
      remark: obj.remark.trim(),
      //配件
      detail: loopList,
      //权限   
      dataAuthority: user.dataAuthorityOfUser,
      appId: [app.globalData.myAppId]  
    }

    //console.log(param);

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.inStorage(param).then(res=>{
      this.setData({
        disabled:false
      })
      if(res.statusCode == 200 && res.data.success == true){
        Toast.success('入库成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //记账人
    if(field=='keepAccounts'){
      this.setData({
        selectTitle: '记账人员',
        showSelectSearch: true
      })
      this.getStaffList();
    }

    //验收人
    if(field=='checking'){
      this.setData({
        selectTitle: '验收人员',
        showSelectSearch: true
      })
      this.getStaffList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //记账人
    if(selectField=='keepAccounts'){
      obj='editInfo.keepAccounts';
    }

    //验收人
    if(selectField=='checking'){
      obj='editInfo.checking';
    }  

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //记账人
    if(selectField=='keepAccounts'){
      obj='editInfo.keepAccounts';
    }

    //验收人
    if(selectField=='checking'){
      obj='editInfo.checking';
    }

    if(id && name){
      this.setData({
        [id]:null,
        [name]:''
      })
    }

    if(obj){
      this.setData({
        [obj]:null
      })
    }

    this.onCloseSelect();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //记账人/验收人
    if(selectField=='keepAccounts' || selectField=='checking'){
      this.getStaffList();
    }  
  },

  //查询人员
  getStaffList(){
    let param = {
      isAuth: false,
      className: 'user',
      data: {
        searchAll: true,
        depart: 1,
        selectFields: ['id','userName']
      }
    }

    if(this.data.valueSearch){
      param.data.userName='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.userName,
            id: item.id,
            obj:{
              id: item.id,
              name: item.userName
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //获取输入的值
  onGetValue(e){
    let dataset=e.currentTarget.dataset;
    let val=e.detail;
    let list=this.data.loopList;

    list.forEach((item,index) => {
      if(index==dataset.index){
        item[dataset.field]=val.trim();
      }
    });

    this.setData({
      loopList: list,
      disabled: false
	  })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})